package wjh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import wjh.pojo.Admin;
import wjh.pojo.Doctor;
import wjh.pojo.Patient;
import wjh.service.AdminInfoService;
import wjh.service.DoctorInfoService;
import wjh.service.UserInfoService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@Controller
@RequestMapping("/loginUser")
public class LoginController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private DoctorInfoService doctorInfoService;

    @RequestMapping("/userLogin")
    public String handleLogin(@RequestParam("name") String name,
                              @RequestParam("password") String password,
                              @RequestParam("captcha") String captcha,
                              HttpSession session, HttpServletRequest request, Model model) {
        Patient patient = userInfoService.findUserLogin(name,password);
        model.addAttribute("patient",patient);
        String correctCaptcha = (String) session.getAttribute("captcha");
        if (patient!=null){
            if (correctCaptcha != null && correctCaptcha.equals(captcha)) {
                Patient patient1 = userInfoService.findUserId(name,password);
                if (patient1.getAvatar()!=null||patient1.getAge()!=null||patient1.getAddress()!=null||patient1.getSex()!=null||patient1.getPhone()!=null){
                    int id=patient1.getId();
                    model.addAttribute("id",id);

                    HttpSession session1 = request.getSession();
                    session1.setAttribute("isLoggedIn", true);

                    return "forward:/jsp/userIndex.jsp";
                }else {
                    int id=patient1.getId();
                    model.addAttribute("id",id);
                    return "forward:/jsp/userInfo.jsp";
                }

            } else {
                model.addAttribute("message", "验证码错误！");
                return "login";
            }
        }else {
            model.addAttribute("message", "用户名密码错误！");
            return "login";
        }
    }
    @RequestMapping("/userRegister")
    public String handleLogin1(@RequestParam("name") String name,
                              @RequestParam("password") String password,
                              @RequestParam("captcha") String captcha,
                              HttpSession session,HttpServletRequest request, Model model) {
        Patient patient = userInfoService.findUserRegister(name);
        String correctCaptcha = (String) session.getAttribute("captcha");
        if (patient==null){
            if (correctCaptcha != null && correctCaptcha.equals(captcha)) {
                userInfoService.register(name,password);
                HttpSession session2 = request.getSession();
                session2.setAttribute("isLoggedIn", true);
                return "login";
            } else {
                model.addAttribute("message", "验证码错误！");
                return "registerP";
            }
        }else {
            model.addAttribute("message", "用户名已存在，请重新注册！");
            return "registerP";
        }
    }

    @RequestMapping("/doctorLogin")
    public String handleLogins(@RequestParam("phone") String phone,
                              @RequestParam("password2") String password,
                              @RequestParam("captcha2") String captcha,
                              HttpSession session,HttpServletRequest request, Model model) {
        Doctor doctor = doctorInfoService.findDoctorLogin(phone,password);
        model.addAttribute("doctor",doctor);
        String correctCaptcha = (String) session.getAttribute("captcha");
        if (doctor!=null){
            if (correctCaptcha != null && correctCaptcha.equals(captcha)) {
                Doctor doctor1 = doctorInfoService.findDoctorId(phone,password);
                if (doctor1.getName()!=null||doctor1.getPhoto()!=null||doctor1.getAge()!=null||doctor1.getSex()!=null||doctor1.getDuty()!=null||doctor1.getDepartment()!=null||doctor1.getIntroduction()!=null){
                    int id=doctor1.getId();
                    model.addAttribute("id",id);
                    HttpSession session1 = request.getSession();
                    session1.setAttribute("isLoggedIn", true);
                    return "forward:/jsp/doctorIndex.jsp";
                }else {
                    int id=doctor1.getId();
                    model.addAttribute("id",id);
                    return "forward:/jsp/doctorInfo.jsp";
                }
            } else {
                model.addAttribute("message", "验证码错误！");
                return "login";
            }
        }else {
            model.addAttribute("message", "手机号密码错误！");
            return "login";
        }
    }
    @RequestMapping("/doctorRegister")
    public String handleLogins1(@RequestParam("phone") String phone,
                               @RequestParam("password2") String password,
                               @RequestParam("captcha2") String captcha,
                               HttpSession session, HttpServletRequest request, Model model) {
        Doctor doctor = doctorInfoService.findDoctorRegister(phone);
        String correctCaptcha = (String) session.getAttribute("captcha");
        if (doctor==null){
            if (correctCaptcha != null && correctCaptcha.equals(captcha)) {
                doctorInfoService.register(phone,password);
                HttpSession session1 = request.getSession();
                session1.setAttribute("isLoggedIn", true);
                return "login";
            } else {
                model.addAttribute("message", "验证码错误！");
                return "registerD";
            }
        }else {
            model.addAttribute("message", "手机号已注册，请重试！");
            return "registerD";
        }
    }

    @RequestMapping("/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        BufferedImage bufferedImage = new BufferedImage(150, 50, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, 150, 50);

        String captchaCode = generateRandomString(5);
        session.setAttribute("captcha", captchaCode);

        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("Arial", Font.BOLD, 30));
        g2d.drawString(captchaCode, 20, 35);

        g2d.dispose();
        OutputStream os = response.getOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        os.flush();
    }

    private String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            captcha.append(characters.charAt(index));
        }
        return captcha.toString();
    }
}
